﻿#define _CRT_SECURE_NO_WARNINGS 1

#include "Contact.h"
#include "SList.h"

//读取历史数据
void LoadContact(Contact** con)
{
	FILE* pf = fopen("Contact.txt", "rb");
	if (pf == NULL)
	{
		perror("fopen error!\n");
		return;
	}

	//循环读取⽂件数据
	PeoInfo info;
	while (fread(&info, 1, sizeof(info), pf))
	{
		SLTPushBack(con, info);
	}
	printf("成功导入通讯录！\n");
}
//初始化通讯录
void InitContact(Contact** con)
{
	LoadContact(con);
}
//添加通讯录数据
void AddContact(Contact** con)
{
	PeoInfo info;
	printf("请输入姓名:\n");
	scanf("%s", &info.name);
	printf("请输入性别:\n");
	scanf("%s", &info.sex);
	printf("请输入年龄:\n");
	scanf("%d", &info.age);
	printf("请输入电话:\n");
	scanf("%s", &info.tel);
	printf("请输入地址:\n");
	scanf("%s", &info.addr);
	printf("请输入邮箱:\n");
	scanf("%s", &info.mailbox);
	
	SLTPushBack(con, info);
	printf("插入成功！\n");
}
//查找联系人(通过姓名)
Contact* FindByName(Contact* con, char name[])
{
	Contact* tmp = con;
	while (tmp)
	{
		if (strcmp(tmp->data.name, name) == 0)
		{
			return tmp;
		}
		tmp = tmp->next;
	}
	return NULL;
}
//删除通讯录数据
void DelContact(Contact** con)
{
	char name[NAME_MAX];
	printf("请输入要删除联系人的名字:\n");
	scanf("%s", name);

	Contact* pos = FindByName(*con, name);
	if (pos == NULL)
	{
		printf("要删除的用户不存在，删除失败！\n");
		return;
	}
	SLTErase(con, pos);
	printf("删除成功!\n");
}
//展⽰通讯录数据
void ShowContact(Contact* con)
{
	printf("%-10s %-5s %-10s %-15s    %-20s %-20s\n", "姓名", "性别", "年龄", "联系电话", "住址", "邮箱");
	Contact * cur = con;
	while (cur)
	{
		printf("%-10s %-5s %-10d %-15s    %-20s %-20s\n",
			cur->data.name,
			cur->data.sex,
			cur->data.age,
			cur->data.tel,
			cur->data.addr,
			cur->data.mailbox);
		cur = cur->next;
	}
}
//查找通讯录数据
void FindContact(Contact* con)
{
	char name[NAME_MAX];
	printf("请输入要查找的用户姓名：n");
	scanf("%s", name);

	Contact* pos = FindByName(con, name);
	if (pos == NULL)
	{
		printf("要查找的用户不存在，查找失败！\n");
		return;
	}
	printf("查找成功!\n");
	printf("%-10s %-5s %-10d %-15s    %-20s %-20s\n\n",
		pos->data.name,
		pos->data.sex,
		pos->data.age,
		pos->data.tel,
		pos->data.addr,
		pos->data.mailbox);
}
//修改通讯录数据
void ModifyContact(Contact** con)
{
	char name[NAME_MAX];
	printf("请输入要修改联系人的名字:\n");
	scanf("%s", name);

	Contact* pos = FindByName(*con, name);
	if (pos == NULL)
	{
		printf("要修改的用户不存在，修改失败！\n");
		return;
	}
	printf("请输入要修改的姓名:\n");
	scanf("%s", pos->data.name);
	printf("请输⼊要修改的性别：\n");
	scanf("%s", pos->data.sex);
	printf("请输⼊要修改的年龄：\n");
	scanf("%d", &pos->data.age);
	printf("请输⼊要修改的联系电话：\n");
	scanf("%s", pos->data.tel);
	printf("请输⼊要修改的地址：\n");
	scanf("%s", pos->data.addr);
	printf("请输⼊要修改的邮箱：\n");
	scanf("%s", pos->data.mailbox);

	printf("修改成功！\n");
}
//将通讯录的内容保存到文件中
void SaveContact(Contact* con)
{
	FILE* pf = fopen("Contact.txt", "wb");
	if (pf == NULL)
	{
		perror("fopen error!\n");
		return;
	}
	Contact* cur = con;
	while (cur)
	{
		fwrite(&(cur->data), sizeof(cur->data), 1, pf);
		cur = cur->next;
	}

	printf("通讯录数据保存完成!\n");
}
//销毁通讯录数据
void DestroyContact(Contact** con)
{
	SaveContact(*con);
	SListDesTroy(con);
}